<template>
  <div>
    <van-field
      readonly
      clickable
      label="门诊"
      :value="label"
      placeholder="请选择门诊"
      @click="showTownPicker = true"
      :rules="[{ required: true, message: '请选择门诊' }]"
    />

    <!-- 街道picker -->
    <van-popup v-model="showTownPicker" position="bottom" get-container="body">
      <van-picker
        show-toolbar
        value-key="label"
        :columns="clinicColumns"
        @cancel="showTownPicker = false"
        @confirm="onConfirmTown"
      />
    </van-popup>
  </div>
</template>

<script>
import { getArea, selectClinic } from "@/api/user.js";
import Bus from "@/components/area/bus";
export default {
  data() {
    return {
      townVal: this.value,
      label: undefined,
      showTownPicker: false,
      clinicColumns: []
    };
  },
  props: {
    value: {}
  },
  watch: {
    value(val) {
      let item = this.clinicColumns.filter(m => m.value == this.townVal)[0];
      this.label = item ? item.label : '';
    }
  },
  created() {
    const _this = this;
    Bus.$on("areaChange", function(code) {
      if (code) {
        const provinceId = code[0].substr(0, 2);
        const cityId = code[1].substr(2, 2);
        const countyId = code[2].substr(4, 2);

        selectClinic({
          provinceId,
          cityId,
          countyId
        }).then(({ data }) => {
          _this.clinicColumns = data.map(m => ({
            label: m.name,
            value: m.clinicId
          }));
        });
      } else {
        _this.clinicColumns = [];
      }
    });
  },
  destroyed() {
    Bus.$off("areaChange");
  },
  methods: {
    onConfirmTown(obj) {
      this.$emit("input", obj.value);
      this.showTownPicker = false;
      this.townVal = obj.value;
    }
  },
  components: {}
};
</script>

<style lang='scss'>
</style>
